import { routes } from '@/router'

export default {
  namespaced: true,
  state: {
    // 访问的标签数组
    visitedViews: [{ path: '/dashboard', name: '工作台' }]
  },
  mutations: {
    // menu点击触发
    changeViews (state, payload) {
      // 通过传来的 path，找到对应的 label
      const name = routes[1].children.find(item => item.path === payload || item.name === payload || item.name === payload.substring(0, 19) + ':id').meta.label
      // 避免添加重复的标签
      if (!state.visitedViews.some(item => item.path === payload)) {
        state.visitedViews.push({ path: payload, name })
      }
    },
    // 删除标签触发
    removeTagFn (state, payload) {
      // 如果存在的话就 删除
      if (state.visitedViews.some(item => item.path === payload.path)) {
        state.visitedViews = state.visitedViews.filter(item => item.path !== payload.path || item.name !== payload.name)
      }
    },

    // 下拉菜单 点击触发
    // 关闭全部标签
    closeAllFn (state) {
      state.visitedViews = [{ path: '/dashboard', name: '工作台' }]
    },
    // 关闭其他标签 除了首页
    closeOthersFn (state, payload) {
      state.visitedViews = state.visitedViews.filter(item => item.path === payload || item.path === '/dashboard')
    },
    // 关闭左侧标签 除了首页
    closeLeftFn (state, payload) {
      const index = state.visitedViews.findIndex(item => item.path === payload)
      state.visitedViews.splice(1, index - 1)
    },
    // 关闭左侧标签
    closeRightFn (state, payload) {
      const index = state.visitedViews.findIndex(item => item.path === payload)
      state.visitedViews.splice(index + 1, state.visitedViews.length)
    }
  },
  actions: {
    // menu点击触发
    changePage (context, payload) {
      context.commit('changeViews', payload)
    },
    // 删除标签触发
    removeTag (context, payload) {
      context.commit('removeTagFn', payload)
    },

    // 下拉菜单 点击触发
    // 关闭全部标签
    closeAll (context, payload) {
      context.commit('closeAllFn')
    },
    // 关闭其他标签
    closeOthers (context, payload) {
      context.commit('closeOthersFn', payload)
    },
    // 关闭左侧标签
    closeLeft (context, payload) {
      context.commit('closeLeftFn', payload)
    },
    // 关闭右侧标签
    closeRight (context, payload) {
      context.commit('closeRightFn', payload)
    }
  }
}
